import streamlit as st
import utills
import os
import pandas as pd
import pygwalker as pyg
import subprocess

from pygwalker.api.streamlit import StreamlitRenderer
import extra_streamlit_components as stx
from annotated_text import annotated_text
from streamlit_image_coordinates import streamlit_image_coordinates
# Set page configuration to hide the sidebar on load
st.set_page_config(layout="wide")
upload_folder = "./upload/video_input/"
landmarks_folder = "./landmarks"
visualize_folder = "./visualize"
if "mainState" not in st.session_state:
    st.session_state.mainState = "Unupload"


def exec_threading(function):
    exec_anlze = utills.ThreadExecutor(function)
    #开始线程
    exec_anlze.start()

    #线程等待
    exec_anlze.join()

def clear_folder(folder_path):
    # 获取文件夹中的所有文件和子文件夹
    files = os.listdir(folder_path)
    if not files:  # 如果文件夹为空
        return "文件夹内无文件"
    for file in files:
        # 构建文件/文件夹的完整路径
        file_path = os.path.join(folder_path, file)
        # 如果是文件，则删除
        if os.path.isfile(file_path):
            os.remove(file_path)
        # 如果是文件夹，则递归清空
        elif os.path.isdir(file_path):
            clear_folder(file_path)


with st.sidebar: 
    st.header("图像变换检测辅助模块")
    st.markdown("• SIFT：")
    st.markdown("_说明：本模块使用SIFT+聚类算法实现，用于检测图像中复制粘贴类篡改_")
    st.markdown("• LSB：")
    st.markdown("_说明：本模块提取并展示图像通道低位信息，对纯色拼接、压缩、低位隐写进行检查_")
    st.markdown("• ELA:")
    st.markdown("_说明：本模块通过比较有损压缩前后图像细微变化，实现对图像的错误水平分析_")
    st.markdown("• Noise_variance:")
    st.markdown("_说明：本模块通过分块提取图像方差+聚类方法实现，用于突出异常方差区域，辅助拼接类篡改痕迹发现_")


headCol = st.columns([1,1,1])
with headCol[1]:
     image_url = ""
     stx.bouncing_image(image_source=image_url, animate=False, animation_time=1500, height=200, width=250)



Buttoncontainer = st.container()

with Buttoncontainer:
    ButtonCol = st.columns([3,2,2])

    with ButtonCol[1]:
        st.write("")
        mybutton = st.button("清除残余文件")
        if mybutton:
            folder_path = "./upload/video_input"  # 替换为您要清空的文件夹路径
            #清空视频输入
            clear_folder(folder_path)
            #清空landmark
            clear_folder(landmarks_folder)
            #清空visualize
            clear_folder(visualize_folder)
            st.session_state.uploadState = "Unupload"
            clear_folder("./upload")

            images_folder_path = "./upload/images"  # 替换为您要清空的文件夹路径
            #清空page2图片输入
            clear_folder(images_folder_path)
            st.session_state.Page3uploadState = "Unupload"
            st.success("文件夹已清空！")
            st.session_state.VideoState = "none"
            st.session_state.PhotoState = "none"
            st.session_state.mainState = "Unupload"
            st.session_state.WelcomeState = "Unupload"
            if os.path.exists("/home/xinan-works/complex_layout_example.pdf"):
                os.remove("/home/xinan-works/complex_layout_example.pdf")
                print(f"文件 pdf 删除成功")
            else:
                print("文件不存在，无法删除")


FirstCol = st.columns([3,10,3])

with FirstCol[1]:
    uploaded_file_1 = st.file_uploader("")
    if os.path.exists('./res/forgery_result.jpg'):
        os.remove('./res/forgery_result.jpg')
    if uploaded_file_1 is not None:
        # 获取上传文件的后缀
        file_extension = '.' + uploaded_file_1.name.split('.')[-1]

        # 实例化文件名生成器并根据文件后缀确定文件名
        file_name_generator = utills.FileNameGenerator(file_extension)

        # 使用生成的文件名保存上传的文件
        with open(f"./upload/{file_name_generator.file_name}", "wb") as f:
            f.write(uploaded_file_1.getvalue())
        st.session_state.mainState = "uploaded"






if st.session_state.mainState == "uploaded":


    DataCol = st.columns(1)
    with DataCol[0]:
        with st.container(border=True):
            AnalyzeCol = st.columns(2)
            with AnalyzeCol[0]:
                with st.container(border=True):
                    if uploaded_file_1 is not None:
                        exec_threading(utills.analyze_image(f"./upload/{file_name_generator.file_name}",
                                                                                        f"./res/result.txt"))

                        with open(f"./res/result.txt", "r") as file:
                            lines = file.readlines()
                            dimensions = lines[0].strip()
                            mode = lines[1].strip()
                            exif_data = lines[2].strip()
                            iptc_data = lines[3].strip()

                        utills.show_image(f"./upload/{file_name_generator.file_name}")
            with AnalyzeCol[1]:
                with st.container(border=True):
                    if uploaded_file_1 is not None:
                        st.write("## 原图参数")
                        st.write(f"### {dimensions}")
                        st.write(f"### {mode}")
                        st.write(f"### Exif Data: {exif_data}")
                        st.write(f"### IPTC Data: {iptc_data}")
            SecoCol = st.columns(2)
            if uploaded_file_1 is not None:
                with SecoCol[0]:
                    st.header("Copy-move检查子模块")
                    with st.container(border=True):
                            exec_SIFTForgeryDetector = utills.ThreadExecutor(utills.Do_SIFTForgeryDetector(f"./upload/{file_name_generator.file_name}"))
                            #开始线程
                            exec_SIFTForgeryDetector.start()
                            
                            exec_SIFTForgeryDetector.join()
                            try:
                                utills.show_image("./res/forgery_result.jpg")
                            except:
                                st.error("No evidence of forgery found in the image.")
            if uploaded_file_1 is not None:
                with SecoCol[1]:
                    st.header("噪声方差提取子模块")
                    with st.container(border=True):
                            exec_threading(utills.detect_noise_variance(f"./upload/{file_name_generator.file_name}",blockSize=32))
                            utills.show_image('./res/noise_res.jpg')

            ThridCol = st.columns(2)
            if uploaded_file_1 is not None:
                with ThridCol[0]:
                    st.header("图像错误水平分析子模块")
                    with st.container(border=True):
                            exec_threading(utills.ela_analysis(f"./upload/{file_name_generator.file_name}"))
                            utills.show_image("./res/ela/difference_scaled.png")
            if uploaded_file_1 is not None:
                with ThridCol[1]:
                    st.header("低位通道提取子模块")
                    with st.container(border=True):
                        
                            exec_threading(utills.Do_ExtractLSB(f"./upload/{file_name_generator.file_name}"))
                            utills.show_image("./res/lsb_result.png")
                

        

                    